define(["common"], function() {
	var sel = {
		// 选项卡相关	
		tabs: "#saletabs",
		tab: function(id) {return id !== undefined?("#sale_" + id) : "[id^='sale_']";},
		
		// 账户相关
		clientInfo: "#clientInfo",
		clientLogin: "#clientLogin",
		aForm: "#accountForm",
		lname: "#lname",
		aName: "#accountName",
		aPin: "#accountPin",
		aBt: function(id) {return id !== undefined?("#accountBt_" + id):"[id^='accountBt_']";},
		clientName: "#clientName",
		clientBalance: "#clientBalance",
		
		// 商品录入相关
		typeinBt: function(id) {return id !== undefined?("#typeinBt_" + id):"[id^='typeinBt_']";},
		type: function(id) {return id !== undefined?("#type_" + id):"[id^='type_']";},
		putupBt: "#putupBt",
		delBt: "#delBt",
		codeForm: "#codeForm",
		lcode: "#lcode",
		code: "#code",
		subtotal: "#subtotal",
		manualBt: function(id) {return id !== undefined?("#manualBt_" + id):"[id^='manualBt_']";},
		totalMoney: "#totalMoney",
		
		// 商品筛选相关
		filter: "#filterGoods",
		filterBody: "#filterGoods tbody",
		filterGoods: function(id) {return id !== undefined?("#filter_" + id):"[id^='filter_']";},
		
		// 购买商品列表相关
		listForm: "#goodsesForm",
		serialCode: "#serialCode",
		listTitle: "#listTitle",
		listBody: "#goodslist tbody",
		listGoods: function(id) {return id !== undefined?("#goods_" + id):"[id^='goods_']";},
		id: function(id) {return id !== undefined?("#id_" + id):"[id^='id_']";},
		tnum: "[id^='tnum_']",
		tprice: function(id) {return id !== undefined?("#tprice_" + id):"[id^='tprice_']";},
		amount: function(id) {return id !== undefined?("#amount_" + id):"[id^='amount_']";},
		cost: function(id) {return id !== undefined?("#cost_" + id):"[id^='cost_']";},
		tcost: function(id) {return id !== undefined?("#tcost_" + id):"[id^='tcost_']";},
		tcode: function(id) {return id !== undefined?("#tcode_" + id):"[id^='tcode_']";},
		delGoodsBt: function(id) {return id !== undefined?("#delGoods_" + id):"[id^='delGoods_']";},
		
		// 结算相关
		settleForm: "#settleForm",
		lreceived: "#lreceived",
		received: "#received",
		returned: "#returned",
		treturned: "#treturned",
		finishBt: function(id) {return id !== undefined?("#finishBt_" + id):"[id^='finishBt_']";},
		
		// 打印相关
		printFrame: "#printframe"
		
	};

	//挂起单数累计
	var saleNum = 0;
	// 当前销售单ID
	var curSerialCode = null;
	// 商品筛选列表对应的数据
	var filterDatas = [];
	// 焦点类型,用于辅助键盘事件处理
	var focusTypes = {
		ADD: "add",				// 查找商品
		FILTER: "filter",		// 筛选商品
		SUBTOTAL: "subtotal", 	// 填写商品金额
		AMOUNT: "amount",		// 修改商品购买量
		SETTLE: "settle"		// 结算
	};
	// 当前焦点
	var focusType = focusTypes.ADD;
	// 商品筛选列表模板内容
	var filterTemp = $(sel.filterBody).html();	
	// 商品记录模板内容
	var itemTemp = $(sel.listBody).html();
	
	$(sel.filterBody).empty();
	$(sel.listBody).empty().show();
	
	loadjs(["validator"], initValidate);
	initEvent();
	initSaleList();
	
	/**
	 * 首进页面初始化
	 */
	function initValidate() {
		$.validator.config({
			stopOnError: true,
			msgMaker: false,
			invalid: function(form, errors) {
				showMsg(errors[0], "error");
			},
			messages: {required: '{0}不能为空'}
		});
		
		$(sel.aForm).validator({
			fields: {
				name: "用户名:required;",
				pin: "PIN码:required;digits"
			},
			valid: function(form) {
				accountDo(form);
			}
		});
		
		// 编码添加商品表单验证
		$(sel.codeForm).validator({
			fields: {
				"#code": "商品编码:required;digits; match[gt, 0]"
			},
			valid: function(form) {
				addGoods();
			}
		});
		
		// 商品列表表单验证
		initGoodsesValid();
		
		// 结算表单验证
		$(sel.settleForm).validator({
			rules: {
				received: function(el) {
					if (!this.test(el, 'money')) {
						return "实收金额无效";
					}
					if (parseFloat($(el).val()) < parseFloat($(sel.totalMoney).html())) {
						return "实收金额不足";
					}
				}
			},
			fields: {
				received: "实收:required;received"
			},
			valid: function(form) {
				settleDo();
			}
		});
		
	}


	function initEvent() {
		
		// 关联用户
		$(sel.aBt()).click(function() {
			$(sel.aForm).trigger('validate');
		});
		// 修改用户
		$(sel.clientName).click(function() {
			$(sel.clientInfo).hide();
			$(sel.clientLogin).show();
		});
		// 进入结账模式
		$(sel.typeinBt('settle')).click(function() {
			var $this = $(this);
			// 列表表单验证通过后再触发完成提交
			initGoodsesValid(function() {

				$(sel.typeinBt()).removeClass("selected");
				$this.addClass("selected");
				$(sel.type()).hide();
				
				// add、settle
				var type = ($this.attr("id").split("_"))[1];
				$(sel.type(type)).show();
				
				// 结账进行时不能编辑商品购买量
				$(sel.amount()).prop("readonly", true);
				
				focusType = focusTypes.SETTLE; 
				$(document).click();
				
			});
			$(sel.listForm).trigger('validate');
			return false;
		});
		// 进入添加商品模式
		$(sel.typeinBt("add")).click(function() {
			//	商品模式下商品数量可编辑
			$(sel.amount()).prop("readonly", false);
			
			$(sel.typeinBt()).removeClass("selected");
			$(this).addClass("selected");
			$(sel.type()).hide();
			
			// add、settle
			var type = ($(this).attr("id").split("_"))[1];
			$(sel.type(type)).show();
			
			focusType = focusTypes.ADD; 
			$(document).click();
			return false;
		});
		// 手工添加商品
		$(sel.manualBt()).click(function() {
			$(sel.codeForm).trigger('validate');
			return false;
		});
		// 选择商品(编码查询有多个结果时)
		$(document).on('click', sel.filterGoods(), function() {
    		var i = $(this).attr("id").split("_")[1];
    		selectFilterGoods(filterDatas[i]);
    		return false;
    	});
		// 填写金额
		$("[id^='subtotalBt_']").click(function() {
			$("#subtotalForm").trigger('validate');
			return false;
		});
		// 完成订单
		$(sel.finishBt()).click(function() {
			// 列表表单验证通过后再触发完成提交
			initGoodsesValid(function() {
				$(sel.settleForm).trigger('validate');
			});
			$(sel.listForm).trigger('validate');
			return false;
		});
		// 计算找零
		$(sel.received).keyup(function() {
			var returned = parseFloat($(this).val()) - parseFloat($(sel.totalMoney).html());
			if (isNaN(returned) || returned < 0) {
				returned = 0;
			}
			$(sel.returned).val(returned.toFixed(2));
			$(sel.treturned).html(returned.toFixed(2));
			return false;
		});
		// 挂起
		$(sel.putupBt).click(function() {
			initGoodsesValid();
			$(sel.listForm).trigger('validate');
			return false;
		});
		// 取消
		$(sel.delBt).click(function() {
			delDo();
			return false;
		});
		
		// 修改购买数量
		$(document).on('keyup',sel.amount(), function() {
			var id = ($(this).attr("id").split("_"))[1];
			var cost = parseFloat($(this).val()) * parseFloat($(sel.tprice(id)).html());
			$(sel.cost(id)).val(cost.toFixed(2));
			$(sel.tcost(id)).html(cost.toFixed(2));
			stat();
			return false;
		});
		// 数量验证失败
		$(document).on('invalid.field', sel.amount(), function(e, result, me){
			// 闪动行
			flickerRow($(this).attr("id").split("_")[1]);
			return false;
		});
		// 删除商品
		$(document).on('click',sel.delGoodsBt(), function() {
			var id = ($(this).attr("id").split("_"))[1];
			$(sel.listGoods(id)).fadeOut(function(){
				$(sel.listGoods(id)).remove();
				stat();
				resetNums();
			});
			return false;
		});
		
		$(document).click(function(event) {
			// 进行其它非录入操作时，使指定文本框获得焦点
			if (!$(event.target).is("input")) {
				if (focusType == focusTypes.ADD) {
					$(sel.code).focus().select();
				} else if (focusType == focusTypes.SUBTOTAL) {
					$(sel.subtotal).focus().select();
				} else if (focusType == focusTypes.SETTLE) {
					$(sel.received).focus().select();
				}
			}
		});

	}
	
	
	/**
	 * 获取销售单(ID)列表
	 */ 
	function initSaleList() {
		showMsg("请稍候...", 'load');
		$.get(g_contextPath + "/ids/json", function(data) {
			showMsg().hide();
			if (data.status !== 0) {
				showMsg(data.message, 'error');
				return;
			}
			var list = data.result;
			var sale = null;
			for (var i in list) {
				saleNum++;
				sale = list[i];
				$(sel.tabs).append('<li id="sale_' + sale.serialCode + '"><a href="#">订单' + saleNum + '</a></li>');
			}
			initEvent_();
			if (sale) {
				activeSale(sale.serialCode);
			} else {
				addNewSale();
			}
		});
		
		function initEvent_() {
			$(document).on('click', sel.tab(), function() {
				if (doing()) return; 
				var serialCode = ($(this).attr("id").split("_"))[1];
				activeSale(serialCode);
				return false;
			});
		}
	}

	/**
	 * 选中(激活)销售单选项卡
	 */
	function activeSaleTab(serialCode) {
		if (!serialCode && $(sel.tab()).length == 0) {
			addNewSale();
			return null;
		} 
		
		var $oldTab = $(sel.tab() + ":has(span)");
		if ($oldTab.length > 0) {
			var oldText = $oldTab.find("span").html();
			$oldTab.html("<a href='#'>" + oldText +  "</a>");
		}
		
		var text = null;
		var $saleTab = null;
		
		if (!serialCode) {
			if ($(sel.tab()).length > 0) {
				$saleTab = $(sel.tab()).eq($(sel.tab()).length - 1);
				text = $saleTab.find("a").html();
				serialCode = $saleTab.attr("id").split("_")[1];
			} else {
				$(sel.tabs).append("<li id='sale_" + serialCode + "'></li>");
				$saleTab = $(sel.tab(serialCode));
				saleNum++;
				text = "订单" + saleNum;
			}
			
		} else {
			$saleTab = $(sel.tab(serialCode));
			if ($saleTab.length > 0) {
				text = $saleTab.find("a").html();
			} else {
				$(sel.tabs).append("<li id='sale_" + serialCode + "'></li>");
				$saleTab = $(sel.tab(serialCode));
				saleNum++;
				text = "订单" + saleNum;
			}
		}
		$saleTab.html("<span>" + text + "</span>");
		return serialCode;
	}
	
	/**
	 * 进入销售单商品出售
	 */
	function activeSale(serialCode) {
		serialCode = activeSaleTab(serialCode);
		if (serialCode) {
			initSale(serialCode);
		}
		
	}
	
	/**
	 * 新建销售单
	 */
	function addNewSale(params, callback) {
		// TODO 允许最多可挂起6个订单
		if ($(sel.tab()).length >= 6) {
			showMsg("已有过多未完成订单", 'error');
			return;
		}
		showMsg("请稍候...", 'load');
		$.post(g_contextPath + "/addDo/json", params, function(data) {
			showMsg().hide();
			if (callback) {
				if (!callback(data)) {
					return;
				}
			}
			if (data.status !== 0) {
				showMsg(data.message, 'error');
				return;
			}
			//var serialCode = data.result;
			activeSale(data.result);
		});
	}

	/**
	 * 初始化销售单显示
	 */
	function initSale(serialCode) {
		curSerialCode = serialCode;
		$(sel.serialCode).val(curSerialCode);
		$(sel.listBody).empty();
		stat();
		loadData();
	}
	
	function accountDo(form) {
		if (doing()) return; 
		showMsg("请稍候...", 'load');
		doing(true);
		var params = $(form).serialize() + "&serialCode=" + curSerialCode;
 		$.post(g_shopDomain + "/fieldSale/bindMemberDo/json", params, function(data) {
			showMsg().hide();
			doing(false);
			if (data.status !== 0) {
				showMsg(data.message, 'error');
				return;
			}
			// memberVip
			var vip = data.result;
			$(sel.clientName).html(vip.member.name);
			$(sel.clientBalance).html(vip.balance ? vip.balance : 0.00);
			$(sel.clientLogin).hide();
			$(sel.clientInfo).show();
			
		});
	}
	
	// 初始化商品列表表单验证
	function initGoodsesValid(callback) {
		var fieldsStr = "{";
		$(sel.amount()).each(function(i, el) {
			fieldsStr += (i > 0 ?"," : "") + "'#" + $(this).attr("id") + "':'数量:required;money'";
		});
		fieldsStr += "}";
		var fields = null;
		eval("fields=" + fieldsStr);
		$(sel.listForm).validator({
			fields: fields,
			valid: function(form) {
				if ($(sel.listForm).find(sel.listGoods()).length === 0) {
					showMsg("请先添加出售商品", 'error');
					return;
				}
				renameForm();
				callback?callback(form):putUpDo(form);
			}
		});
	}
	
	// 加载销售单数据
	function loadData() {
		if (doing()) return; 
		showMsg("请稍候...", 'load');
		doing(true);
		$.post(g_contextPath + "/one/json", {serialCode: curSerialCode}, function(data) {
			showMsg().hide();
			doing(false);
			if (data.status !== 0) {
				showMsg(data.message, 'error');
				return;
			}			
			// fieldSale
			var sale = data.result;
			// memberVip
			var vip = data.result.memberVip;
			// 用户
			if (sale.member) {
				$(sel.clientName).html(sale.member.name);
				$(sel.clientBalance).html(vip ? vip.balance : 0.00);
				$(sel.clientLogin).hide();
				$(sel.clientInfo).show();
			} else {
				$(sel.clientName).html("");
				$(sel.clientBalance).html(0.00);
				$(sel.clientInfo).hide();
				$(sel.clientLogin).show();
			}
			
			var list = sale.fieldSaleGoodses;
			var og;// fieldSaleGoods
			var sg;// storeGoods
			for (var i in list) {
				og = list[i];
				sg = og.storeGoods;
				sg.amount = og.amount;
				sg.cost = og.cost;
				appendGoods(sg);
			}
			
			$(sel.typeinBt('add')).click();
		});
	}
	
	function selectFilterGoods(sg) {
		$(sel.filter).hide();
		
		// 打秤类:
		if (parseInt(sg.barCode) < 100000) {
			showSubtotalForm(sg);
    		return;
		}
		
		appendGoods(sg);
	}
	
	// 显示金额填写表单
	function showSubtotalForm(sg) {
		focusType = focusTypes.SUBTOTAL;
		$("#subtotalDialog").show();
		$(sel.subtotal).focus().val("");
		initSubtotalValid(function(form) {
			$("#subtotalDialog").hide();
			sg.cost = parseFloat($(sel.subtotal).val());
			sg.amount = parseFloat(sg.cost/sg.price);
			appendGoods(sg);
		});
	}
	
	// 初始化商品金额表单验证
	function initSubtotalValid(callback) {
		$("#subtotalForm").validator({
			fields: {
				subtotal: "金额:required;money"
			},
			valid: function(form) {
				callback?callback(form):void(0);
			}
		});
	}
	
	function addGoods() {
		if (doing()) return; 
		showMsg("请稍候...", 'load');
		doing(true);
		
		$(sel.filter).hide();
		$(sel.filterBody).empty();
		
		var barCode = $(sel.code).val();
		$(sel.code).val("");
		$.post(g_contextPath + "/storeGoods/code/json", {barCode: barCode, sort: "barCode"}, function(data) {
			showMsg().hide();
			doing(false);
			$(document).click();// 使焦点回到编码输入框（或者扫描状态）
			if (data.status !== 0) {
				showMsg(data.message, 'error');
				return;
			} 
			// storeGoods list
			var list = data.result;
			if (!list || list.length == 0) {
				showMsg("查无商品", 'error');
				return;
			}
			
			var sg = null;
			if (list.length == 1) {
				
				sg = list[0];
				if (parseInt(sg.barCode) > 99999) {
					appendGoods(sg);
					return;
				} 
				
				var code = parseInt(barCode);
				// 打秤类
				if (code > 2e12 && code < 29e11) {// 从编码中获取金额
					var cost = code%1e6;
					cost = parseInt(cost/10)/100;
					sg.cost = cost;
					sg.amount = parseFloat((cost/sg.price));
					appendGoods(sg);
					
				} else {// 填写金额
					showSubtotalForm(sg);
				}
				
			} else {
				
				filterDatas = list;
				$(sel.filter).show();
				var html;
				for (var i in list) {
					sg = list[i];
					html = filterTemp
					.replace(/\-\{index\}\-/g, i)
					.replace(/\-\{barCode\}\-/g, sg.barCode)
					.replace(/\-\{name\}\-/g, sg.name)
					.replace(/\-\{price\}\-/g, sg.price + "/" + sg.unit);
					$(sel.filterBody).append(html);
				}
				
			}
			
		});
				
	}
	
	function appendGoods(sg) {
		
		if (sg.cost == undefined || sg.amount == undefined) {
			sg.cost = sg.price;
			sg.amount = 1;
		}

		var id = sg.storeGoodsId;
		
		// 列表中已经存在此商品
		if ($(sel.listGoods(id)).length > 0) {
			var preCost = parseFloat($(sel.cost(id)).val());
			var preAmount = parseFloat($(sel.amount(id)).val());
			var cost = sg.cost + preCost;
			var amount = sg.amount + preAmount;
			$(sel.amount(id)).val(amount.toFixed(2));
			$(sel.cost(id)).val(cost.toFixed(2));
			$(sel.tcost(id)).html(cost.toFixed(2));
		} else {
			//sg.unit = sg.sellUnit?sg.sellUnit:sg.unit;
			var itemHtml = itemTemp
			.replace(/\-\{id\}\-/g, id)
			.replace(/\-\{num\}\-/g, $(sel.listGoods()).length + 1)
			.replace(/\-\{code\}\-/g, sg.barCode)
			.replace(/\-\{name\}\-/g, sg.name)
			.replace(/\-\{price\}\-/g, sg.price)
			.replace(/\-\{amount\}\-/g, sg.amount.toFixed(2))
			.replace(/\-\{unit\}\-/g, sg.unit)
			.replace(/\-\{cost\}\-/g, sg.cost.toFixed(2));
			$(sel.listBody).prepend(itemHtml);
		}
		
		stat();
		
		focusType = focusTypes.ADD;
		$(document).click();
	}
	
	function renameForm() {
		var $form = $(sel.listForm);
		// 表单重命名
		$form.find(sel.listGoods()).each(function(i, el) {
			var $tr = $(this);
			var id = ($tr.attr("id").split("_"))[1];
			$tr.find(sel.id(id)).attr("name", "ogs[" + i + "].storeGoodsId");
			$tr.find(sel.amount(id)).attr("name", "ogs[" + i + "].amount");
			$tr.find(sel.cost(id)).attr("name", "ogs[" + i + "].cost");
		});
		return $form;
	}
	
	function settleDo() {
		if (doing()) return; 
		showMsg("请稍候...", 'load');
		var params = $(sel.listForm).serialize() + "&" + $(sel.settleForm).serialize();
		$.post(g_contextPath + "/finishDo/json", params, function(data) {
			if (data.status !== 0) {
				showMsg(data.message, 'error');
				return;
			}
			showMsg("结算成功!", 'pass');
			
			// 打印
			var fw = $(sel.printFrame).get(0).contentWindow;// frame window
			fw.initPrint();
			fw.focus();// (ie兼容)不加则始终打印顶层页面
			fw.print();
			
			// 删除导航标题
			$(sel.tab(curSerialCode)).remove();
			activeSale();
			
		});
	}
	
	function putUpDo() {
		if (doing()) return; 
		showMsg("请稍候...", 'load');
	
		$.post(g_contextPath + "/updateDo/json", $(sel.listForm).serialize(), function(data) {
			if (data.status !== 0) {
				showMsg(data.message, 'error');
				return;
			}
			showMsg("挂起成功!");
			addNewSale();
		});
	}
	
	function delDo() {
		if (doing()) return; 
		showMsg("请稍候...", 'load');
		
		$.post(g_contextPath + "/delDo/json", {serialCode: curSerialCode}, function(data) {
			if (data.status !== 0) {
				showMsg(data.message, 'error');
				return;
			}
			showMsg("删除成功!");
			
			// 删除导航标题
			$(sel.tab(curSerialCode)).remove();
			activeSale();
		});
	}
	
	// 给单中每个商品赋个序号,从大到小
	function resetNums() {
		var $nums = $(sel.tnum);
		var len = $nums.length;
		$nums.each(function(i, el) {
			$(this).html(len - i);
		});
	}
	
	// 统计金额
    function stat() {
    	var money = 0;
    	$(sel.cost()).each(function() {
    		money +=parseFloat($(this).val());
    	});
    	$(sel.totalMoney).html(money.toFixed(1) + "0"); // 金额四舍五入保留一位小数
    	$("#totalMoney1").html(money.toFixed(1) + "0");
    }
    
    // 行闪动
    function flickerRow(id) {
    	$(sel.listGoods(id)).fadeTo('fast',0.1,function() {$(this).fadeTo('fast',1);}); 
    }
    	
	
	/**
	 * 消息提示
	 */
	function showMsg(msg, type) {
		var $el = $('#tip');
		if (!msg)return $el;
		$loading = $el.find(".loading").hide();
	    $el.find(".msg").html(msg);
	    $el.show();
		if (type !== "load") {
	        setTimeout(function() {
	        	showMsg().hide();
	        },1500);
	    } else {
	    	$loading.show();
	    }
	    return $el;
	}

	/**
	 * 快捷键相关
	 */ 
	(function($) {
		var isShowKey_ = false;
		var keys_ = [
			{key: "1", tg: function () { return $(sel.tab()).eq(0).find("a,span");}},
			{key: "2", tg: function () { return $(sel.tab()).eq(1).find("a,span");}},
			{key: "3", tg: function () { return $(sel.tab()).eq(2).find("a,span");}},
			{key: "4", tg: function () { return $(sel.tab()).eq(3).find("a,span");}},
			{key: "5", tg: function () { return $(sel.tab()).eq(4).find("a,span");}},
			{key: "6", tg: function () { return $(sel.tab()).eq(5).find("a,span");}},
			{key: "F3", tg: function () { return $(sel.typeinBt('add'));}},
			{key: "F4", tg: function () { return $(sel.typeinBt('settle'));}},
			{key: "F6", tg: function () { return $(sel.lcode);}},
			{key: "F7", tg: function () { return $(sel.lname);}},
			{key: "F8", tg: function () { return $(sel.lreceived);}},
			{key: "F10", tg: function () { return $(sel.putupBt);}},
			{key: "Del", tg: function () { return $(sel.delBt);}},
			{key: "Enter", tg: function () { return $(sel.manualBt() + "," + sel.finishBt() + "," + sel.aBt());}},
			{key: "Esc", tg: function () { return $("#unfinishBt");}}
		];
		
		$(document).on('showKey', function() {
			showKey_(isShowKey_);
		});
		
		require(["jwerty"], initJwerty_);
		
		// 注册键盘事件
		function initJwerty_() {
			// 订单1-6
			for (var i = 0; i < 6; i++) {
				jwerty.key('alt+' + (i + 1), (function(i) { return function () { $(sel.tab()).eq(i).click(); return false;};}(i)));
			}
			
			// 显示快捷键
			jwerty.key('F1', function () { setTimeout(function () {showKey_(isShowKey_?false:true);}); return false;});
			// 重复打印
			jwerty.key('F2', function () { var fw = $(sel.printFrame).get(0).contentWindow;fw.focus();fw.print(); return false;});
			// 商品模式
			jwerty.key('F3', function () { focusType = focusTypes.ADD; $(sel.typeinBt('add')).click(); return false;});
			// 结算模式
			jwerty.key('F4', function () { focusType = focusTypes.SETTLE; $(sel.typeinBt('settle')).click(); return false;});
			// 填写商品编码
			jwerty.key('F6', function () { $(sel.code).focus(); return false;});
			// 填写用户名
			jwerty.key('F7', function () { $(sel.aName).click().focus(); return false;});
			// 填写实收金额
			jwerty.key('F8', function () { $(sel.received).focus(); return false;});
			// 挂起订单
			jwerty.key('F10', function () { $(sel.putupBt).click(); return false;});
			// 取消订单
			jwerty.key('del', function () { $(sel.delBt).click(); return false;});
			// 选择列表中上一个商品
			jwerty.key('↑', function () { arrowKey_('up'); return false;});
			// 选择列表中下一个商品
			jwerty.key('↓', function () { arrowKey_(); return false;});
			// 删除选中的商品
			jwerty.key('d', function () {
				var curIndex = $(sel.amount()).filter(":focus").index(sel.amount());
				if (curIndex > -1) {
					$(sel.delGoodsBt()).eq(curIndex).trigger('click');
					return false;
				}
			});
			
			jwerty.key('esc', escKey_);
			jwerty.key('enter', enterKey_);
		}
		
		// 显示快捷键
		function showKey_(bool) {
			if (bool || bool === undefined) {
				isShowKey_ = true;
			} else {
				isShowKey_ = false;
			}
			for (var i in keys_) {
				$els = keys_[i].tg();
				$els.each(function(index, el) {
					var $el = $(el);
					if ($el.length > 0) {
	    				if (bool || bool === undefined) {
	    					isShowKey_ = true;
	    					var text = $el.html();
	    					if (!keys_[i].text) {
	    						keys_[i].text = [];
	    					}
	    					if (!keys_[i].text[index]) {
	    						keys_[i].text[index] = text;
	    					}
	    					$el.html(keys_[i].key);
	    				} else if (keys_[i].text) {
	    					$el.html(keys_[i].text[index]);
	    				}
	    			}
				});
			}
		}
		
		function escKey_() {
			if (focusType == focusTypes.ADD) {
				$(sel.filter).hide();
			} else if (focusType == focusTypes.FILTER) {
				focusType = focusTypes.ADD;
				$(sel.filter).hide();
			} else if (focusType == focusTypes.SUBTOTAL) {
				focusType = focusTypes.ADD;
				$("#subtotalDialog").hide();
			} else if (focusType == focusTypes.AMOUNT) {
				focusType = focusTypes.ADD;
				$(sel.listGoods()).removeClass("hover");
			} else if (focusType == focusTypes.SETTLE) {
				focusType = focusTypes.ADD;
				$(sel.typeinBt('add')).click();
			}
			$(document).click();
			return false;
		}
		
		//　回车键处理
		function enterKey_() {
			
			// 筛选商品
			if (focusType == focusTypes.FILTER) {
				
				$(sel.filterGoods()).filter(".hover").click();
				return false;
				
			} // （编辑回来）添加商品
			else if (focusType == focusTypes.ADD) {
				
				// 不输入编辑按回车，则直接进入结算
				if (!$(sel.code).val()) {
					$(sel.typeinBt('settle')).click();
					return false;
				}
				
			} // 填写商品金额
			else if (focusType == focusTypes.SUBTOTAL) {
				
				$("[id^='subtotalBt_']").eq(0).click();
				return false;
				
			} // 修改商品数量
			else if (focusType == focusTypes.AMOUNT) {
				$(sel.listGoods()).removeClass("hover");
				focusType = focusTypes.ADD;
				$(document).click();
				return false;
				
			} // 结算
			else if (focusType == focusTypes.SETTLE) {
				$(sel.finishBt()).eq(0).click();
				return false;
				
			}
			
		}
		
		// 上下箭头键处理
		function arrowKey_(type) {
			
			// 选择查询列表中的商品
			if (focusType == focusTypes.FILTER || (focusType == focusTypes.ADD && $(sel.filter).is(":visible"))) {
				
				focusType = focusTypes.FILTER;
				$(sel.code).blur();
				
				var $items = $(sel.filterGoods());
				var curIndex = $items.filter(".hover").index(sel.filterGoods());
				var nextIndex = 0;
				$items.removeClass("hover");
				if (type === 'up') {
					nextIndex = ((curIndex === -1 || curIndex === 0)  ? $items.length: curIndex) - 1;
				} else {
					nextIndex = (curIndex === $items.length - 1 ? -1 : curIndex) + 1;
				}
				
				var $item = $items.eq(nextIndex); 
				$item.addClass("hover");
				
				// 使显示在可见区域
				var fgt = $(sel.filter + " table").position();
				var ios = $item.position();// itemOffset
				var $container = $(sel.filter);
				if (ios.top < 0) {
					$container.scrollTop(Math.abs(fgt.top - ios.top));
				} else if (ios.top + $item.outerHeight() > $container.height()) {
					$container.scrollTop(Math.abs(fgt.top - $item.outerHeight() - (ios.top - $container.height())));
				}
				
			} // 选择订单列表中的商品(修改数量)
			else if (focusType == focusTypes.AMOUNT || focusType == focusTypes.ADD) {
				
				focusType = focusTypes.AMOUNT;
				
				var $items = $(sel.listGoods());
				var curIndex = $items.filter(".hover").index(sel.listGoods());
				var nextIndex = 0;
				$items.removeClass("hover");
				if (type === 'up') {
					nextIndex = ((curIndex === -1 || curIndex === 0)  ? $items.length: curIndex) - 1;
				} else {
					nextIndex = (curIndex === $items.length - 1 ? -1 : curIndex) + 1;
				}
				
				var $item = $items.eq(nextIndex);
				$item.addClass("hover");
				
				// 数量文本框
				$(sel.amount()).eq(nextIndex).select().click();
				
				// 使显示在可见区域
				var itemOffset = $item.offset();
				var $title = $(sel.listTitle);
				var titleHeight = $title.outerHeight();
				var listOffset = $title.offset();
				if (itemOffset.top < (listOffset.top + titleHeight)) {
					$(window).scrollTop($(window).scrollTop() - (listOffset.top - itemOffset.top) - titleHeight);
				}
			}
			return false;
		}
		
	})($);
	
});
